package com.cayden.components.kafka;


import com.cayden.config.boot.Apps;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;

/**
 * @author cayden
 * @date 2021-10-25 14:43
 */
public class KafkaCondition implements Condition {

    private static Boolean hasMatch = null;

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        if (hasMatch != null && hasMatch.booleanValue()) {
            return true;
        } else if (hasMatch != null && !hasMatch.booleanValue()) {
            return false;
        }
        //1、能获取到ioc使用的beanfactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //2、获取类加载器
        ClassLoader classLoader = context.getClassLoader();
        //3、获取当前环境信息
        Environment environment = Apps.getEnvironment();
        //4、获取到bean定义的注册类
        BeanDefinitionRegistry registry = context.getRegistry();

        String property = environment.getProperty("os.name");
        //此处也可以获取到配置文件的信息,比如获取配置文件中的端口
        String ipPort = environment.getProperty("spring.kafka.producer.bootstrap-servers");

        System.out.println(ipPort);
        URI uri = URI.create("http://" + ipPort);

        String host = uri.getHost();

        int port1 = uri.getPort();

        boolean b = this.isHostConnectable(host, port1);
        if (b) {
            hasMatch = new Boolean(true);
        } else {
            hasMatch = new Boolean(false);
        }
        return b;
    }

    /**
     * 判断kafka服务器，能否正常连接
     *
     * @param host
     * @param port
     * @return
     */
    public boolean isHostConnectable(String host, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port), 2000);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public Boolean getHasMatch() {
        return hasMatch;
    }
}
